﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using com.huigo.Admin.Web.config;
using com.huigo.Admin.Web.Config;
using com.loto.Common;
using com.huigo.Framework.ServiceUtils;
using com.huigo.Framework.Passport;

namespace com.huigo.Admin.Web.user
{
    public partial class AddUser : BasePage
    {
        private bool isModify
        {
            get
            {
                return sid == long.MinValue ? flgModify.Text == "0" ? false : true : true;
            }
        }

        private string username
        {
            get
            {
                if (string.IsNullOrEmpty(Request.QueryString["username"]))
                {
                    return string.Empty;
                }
                else
                {
                    return Request.QueryString["username"];
                }
            }
        }
        private long sid
        {
            get
            {
                if (string.IsNullOrEmpty(Request.QueryString["sid"]))
                {
                    return long.MinValue;
                }
                else
                {
                    long s = long.MinValue;
                    if (long.TryParse(Request.QueryString["sid"], out s))
                        flgModify.Text = "1";
                    return s;
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (isModify)
                {
                    Bind();
                }
                BindData();
            }
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!VerifyField(FieldType.STRING, userRealName.Text, true))
            {
                MessageBox.Show(this.Page, "姓名不能为空！");
                return;
            }
            if (!VerifyField(FieldType.STRING, userDeptList.SelectedValue, true))
            {
                MessageBox.Show(this.Page, "部门不能为空！");
                return;
            }
            if (!VerifyField(FieldType.STRING, userName.Text, true))
            {
                MessageBox.Show(this.Page, "登录账号不能为空！");
                return;
            }
            if (!isModify)
            {
                if (!VerifyField(FieldType.STRING, userPwd.Text, true))
                {
                    MessageBox.Show(this.Page, "登陆密码不能为空！");
                    return;
                }
            }
            string strRights = Request.Form["rights"];
            string strRose = Request.Form["group"];
            if (!string.IsNullOrEmpty(strRose))
            {
                strRose = "," + strRose + ",";
            }
            if (!string.IsNullOrEmpty(strRights))
            {
                SaveConfig(strRights);
            }
            else
            {
                MessageBox.Show(this.Page, "权限不能为空！");
                return;
            }
            List<RequestFuncParams> argList = new List<RequestFuncParams>();
            BaseService baseService = new BaseService();
            ParserXml parser;
            if (isModify)
            {
                argList.Add(new RequestFuncParams("userPart", userDeptList.SelectedValue));
                argList.Add(new RequestFuncParams("userPwd", userPwd.Text));
                argList.Add(new RequestFuncParams("userNum", userMum.Text));
                argList.Add(new RequestFuncParams("userRose", strRose));
                argList.Add(new RequestFuncParams("insStatus", rdoStatus.SelectedValue));
                argList.Add(new RequestFuncParams("creatBY", UserId.ToString()));
                argList.Add(new RequestFuncParams("sid", sid.ToString()));
                if (CheckData())
                {
                    MessageBox.Show(this.Page, "姓名和登陆账号已存在！");
                    return;
                }
                else
                {
                    parser = baseService.RequestEntryService(Dict.ERequestFunc.UPDATE_USER_INFO, argList);
                }
            }
            else
            {
                argList.Add(new RequestFuncParams("userRalName", userRealName.Text));
                argList.Add(new RequestFuncParams("userPart", userDeptList.SelectedValue));
                argList.Add(new RequestFuncParams("userName", userName.Text));
                argList.Add(new RequestFuncParams("userPwd", userPwd.Text));
                argList.Add(new RequestFuncParams("userRose", strRose));
                argList.Add(new RequestFuncParams("insStatus", rdoStatus.SelectedValue));
                argList.Add(new RequestFuncParams("creatBY", UserId.ToString()));
                argList.Add(new RequestFuncParams("userNum", userMum.Text));
                if (CheckData())
                {
                    MessageBox.Show(this.Page, "姓名和登陆账号已存在！");
                    return;
                }
                else
                {
                    parser = baseService.RequestEntryService(Dict.ERequestFunc.ADD_USER_INFO, argList);
                }
            }
            if (parser != null)
                GoTo(GoToType.ADDSUC);

        }
        private bool CheckData()
        {
            List<RequestFuncParams> arglist = new List<RequestFuncParams>();
            arglist.Add(new RequestFuncParams("userName", userName.Text));
            arglist.Add(new RequestFuncParams("ID", sid.ToString()));
            arglist.Add(new RequestFuncParams("userRealName", userRealName.Text));
            BaseService baseService = new BaseService();
            ParserXml parser = baseService.RequestEntryService(Dict.ERequestFunc.GET_USER_INFO_LIST, arglist);
            if (parser != null && parser.RowsCount > 0 && parser["returnargs", 0] == "true")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        private void SaveConfig(string strRights)
        {
            string[] rights = strRights.Split(new char[] { ',' });
            MenuConfig mc = BaseConfig.LoadMenuConfig();
            MenuConfig newMc = new Config.MenuConfig();
            newMc.MenuList = new List<Config.Model.Menu>();
            if (mc != null)
            {
                List<Config.Model.Menu> mList = new List<Config.Model.Menu>();
                foreach (Config.Model.Menu ss in mc.MenuList)
                {
                    Config.Model.Menu menu = new Config.Model.Menu();
                    menu.ID = ss.ID;
                    menu.Name = ss.Name;
                    menu.ParentId = ss.ParentId;
                    menu.RightId = ss.RightId;
                    menu.Url = ss.Url;
                    List<Config.Model.BaseMenu> childMenuList = new List<Config.Model.BaseMenu>();
                    foreach (Config.Model.BaseMenu s in ss.ChildMenu)
                    {
                        for (int i = 0; i < rights.Length; i++)
                        {
                            if (rights[i] != string.Empty && rights[i] == s.ID.ToString())
                            {
                                Config.Model.BaseMenu m = new Config.Model.BaseMenu();
                                m.ID = s.ID;
                                m.Name = s.Name;
                                m.ParentId = s.ParentId;
                                m.RightId = s.RightId;
                                m.Url = s.Url;
                                childMenuList.Add(m);
                            }
                        }
                    }
                    menu.ChildMenu = childMenuList;
                    mList.Add(menu);
                }
                foreach (Config.Model.Menu mm in mList)
                {
                    if (mm.ID == 1)
                    {
                        newMc.MenuList.Add(mm);
                    }
                    else if (mm.ChildMenu != null && mm.ChildMenu.Count > 0)
                    {
                        mm.Url = mm.ChildMenu[0].Url;
                        newMc.MenuList.Add(mm);
                    }
                }
            }

            string configPath = PathHandle.GetFilePath("~/App_Data/" + userName.Text + "MenuConfig.xml");
            XmlSerializer xml = new XmlSerializer(typeof(Config.MenuConfig));
            FileStream fs = new FileStream(configPath, FileMode.Create);
            xml.Serialize(fs, newMc);
            fs.Close();
        }
        private void BindData()
        {
            LoadData();
            //角色
            StringBuilder sb = new StringBuilder();
            string content = "<input  class='groupclass' name=\"group\" type=\"checkbox\" value=\"{0}\" {2}/>{1}";
            List<DropList> UserList = Tools.DictToDropList(Dict.DictUserRole);
            if (UserList != null)
            {                            
                for (int i = 0; i < UserList.Count; i++)
                {
                    bool isMatch = false;    
                    if (!string.IsNullOrEmpty(UserList[i].id))
                    {
                        if (rose != "0")
                        {
                            if (rose.Contains("," + UserList[i].id + ","))
                            {
                                isMatch = true;
                            }
                            if (isMatch)
                            {
                                sb.AppendFormat(content, UserList[i].id, UserList[i].value, "checked=\"checked\"");
                            }
                            else
                            {
                                sb.AppendFormat(content, UserList[i].id, UserList[i].value, "");
                            }
                        }
                        else
                        {
                            sb.AppendFormat(content, UserList[i].id, UserList[i].value, "");
                        }
                    }
                }
                LitRose.Text = sb.ToString();
            }

            //部门
            List<RequestFuncParams> argList = new List<RequestFuncParams>();
            BaseService baseService = new BaseService();                        
            ParserXml parser = baseService.RequestEntryService(Dict.ERequestFunc.GET_USER_DEPT_LIST, argList);
            List<DropList> cDropList = Tools.ParserToDropList(parser, "DeptId", "DeptName");
            if (cDropList != null)
            {
                userDeptList.DataSource = cDropList;
                userDeptList.DataValueField = "Id";
                userDeptList.DataTextField = "Value";
                userDeptList.DataBind();
            }
        }
        private void LoadData()
        {
            string formatDiv = "<div>{0}</div>";
            string formatChildDiv = "<input name=\"rights\" type=\"checkbox\" value=\"{1}\" {2}/>{0}";
            StringBuilder sb = new StringBuilder();
            MenuConfig bmc = BaseConfig.LoadMenuConfig();
            MenuConfig mc = BaseConfig.LoadMenuConfig(username);
            foreach (Config.Model.Menu mm in bmc.MenuList)
            {
                sb.AppendLine(string.Format(formatDiv, mm.Name));
                foreach (Config.Model.BaseMenu m in mm.ChildMenu)
                {
                    int i = BaseConfig.GetMenuId(mc, m.Url);
                    if (i != int.MinValue)
                    {
                        sb.AppendLine(string.Format(formatChildDiv, m.Name, m.ID, "checked=\"checked\""));
                    }
                    else
                    {
                        sb.AppendLine(string.Format(formatChildDiv, m.Name, m.ID, ""));
                    }
                }
            }
            litRight.Text = sb.ToString();
        }
        string rose = string.Empty;
        private void Bind()
        {
            List<RequestFuncParams> argList = new List<RequestFuncParams>();
            argList.Add(new RequestFuncParams("sid", sid.ToString()));
            BaseService baseService = new BaseService();
            ParserXml parser = baseService.RequestEntryService(Dict.ERequestFunc.GET_USER_INFO_BY_ID, argList);
            if (parser != null && parser.RowsCount > 0)
            {
                string RealName = parser["UserRealName", 0].ToString();
                string UserName = parser["UserName", 0].ToString();
                userRealName.Text = RealName;
                userRealName.Enabled = false;
                userName.Text = UserName;
                userName.Enabled = false;
                userDeptList.SelectedValue = parser["UserDeptFid", 0].ToString();
                rdoStatus.SelectedValue = parser["UserIsActive", 0].ToString();
                rose = parser["UserRoleFids", 0].ToString();
                userMum.Text = parser["UserNum", 0].ToString();
            }
        }
    }
}
